import { contextBridge, ipcRenderer, shell } from 'electron'
import type { CustomApi } from './electron-api'
import fs from 'fs-extra'
import { extname, join } from 'path'
import ElectronStore from 'electron-store'

// Custom APIs for renderer
const store = new ElectronStore({ name: 'global-storage' })
const api: CustomApi = {
  getScreenSource() {
    return ipcRenderer.invoke('GET_SCREEN_SOURCE')
  },
  async stat(filePath) {
    const stat = await fs.stat(filePath)
    return {
      isDirectory: stat.isDirectory()
    }
  },
  async readdir(filePath) {
    const dir = await fs.readdir(filePath)
    const maybedir: string[] = []
    const maybeFile: string[] = []
    dir.forEach((v) => {
      const e = extname(v)
      if (e) {
        maybeFile.push(v)
      } else {
        maybedir.push(v)
      }
    })

    maybedir.sort((a, b) => a.localeCompare(b))
    maybeFile.sort((a, b) => a.localeCompare(b))

    return [...maybedir, ...maybeFile]
  },
  fileExits(filePath: string) {
    return fs.pathExists(filePath)
  },
  async readFile(filePath) {
    const stat = await fs.stat(filePath)
    const buffer = await fs.readFile(filePath)
    if (stat.isFile()) {
      return buffer.toString()
    }
    return '!! Not Supported'
  },
  joinFilePath(a, b) {
    return join(a, b)
  },
  open(path: string) {
    return shell.openExternal(path)
  },
  setItem(key: string, value: string) {
    store.set(key, value)
  },
  getItem(key: string) {
    return store.get(key)
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('api', api)
    console.log('register in contextBridge')
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.api = api
}
